<?php
declare (strict_types=1);
/**
 * @Description:
 * @Author: Chern
 * @Date: 2023/7/11
 * @Time: 10:35
 */

namespace app\controller;

use app\BaseController;
use app\message;
use app\model\CluePerson;
use app\model\SystemFieldPower;
use app\model\SystemMenuDataPower;
use app\model\SystemOperateLog;
use app\model\User;
use app\model\UserOrganization;
use app\service\Power;
use app\service\RedisService;
use app\validate\Menu;
use app\validate\User as userV;
use think\exception\ValidateException;
use think\facade\Cache;
use app\model\SystemMenu;
use app\model\UserPosition;
use app\Request;
use app\service\System;
use app\stateData;
use think\App;
use think\facade\Db;
use think\facade\Log;
use think\facade\Validate;
use Complex\Exception;


class SystemUser extends BaseController
{

    /**
     * 用户权限控制器
     */

    private $operateLog;

    private $user;

    public function __construct(App $app, SystemOperateLog $operateLog, User $user)
    {
        parent::__construct($app);

        $this->operateLog = $operateLog;

        $this->user = $user;
    }

    //个人中心
    public function getUserInfo(Request $request,User $user,System $systemService,UserOrganization $organizationModel)
    {
        $id = $request->param('user_login_id');

        if (empty($id)) return ReJson (message::$ERROR_CODE,message::$ERR_PARAM_EMPTY);

        $result = $user->getIdUserData($id);
        //获取用户公司
        if ($result){
            if (!$result['department_id']['id']) {
                $result['company_name'] = '';
            }else{
                $result['company_name'] = $organizationModel->getStructureName ($systemService->getOrgZgsId($result['department_id']['id']));
            }
        }
        return ReJson (message::$SUCC_CODE,message::$SUCC_SELECT_DATA,$result);
    }

    //更新用户头像
    public function setUserImg(Request $request,User $user)
    {
        $id = $request->param('user_login_id');

        $param = $request->post ();

        $file = $request->file('file');

        if (empty($id) || empty($param['password'])) return ReJson (message::$ERROR_CODE,message::$ERR_PARAM_EMPTY);

        if (!empty($file)){
            $param['up_img'] = \think\facade\Filesystem::disk('public')->putFile( 'topic', $file);
        }

        if ($param['mobile']){
            if (!isMobile($param['mobile'])){
                return ReJson (message::$ERROR_CODE,"手机号码格式错误");
            }
        }

        //查询未做更改之前的数据
        $uData = $user->getIdUserData ($id);

        if ($uData['password'] == $param['password']){
            //未更改密码不做密码更新
            unset($param['password']);
        }
        $user->systemSave($param);

        //判断是否修改了密码 修改的话退出登陆
        if (isset($param['password'])){
            Db::table('login_token')->where (['uid'=>$id])->delete ();
        }

        $result = $user->getIdUserData ($id);

        return ReJson (message::$SUCC_CODE,message::$SUCC_UPDATE,$result);

    }

    //获取初始化列表
    public function getAuthorityList(UserPosition $model,SystemMenu $menuModel,System $system)
    {
        //获取角色列表
        $result['levelList'] = $model->getLevelList();

        $result['menuList'] = $system->menuTreeList ($menuModel->getMenuList());

        $result['Kjfw'] = stateData::$_kjfw;  //暂定 可见范围

        return ReJson(message::$SUCC_CODE,message::$SUCC_SELECT_DATA,$result);

    }


    //获取职位对应菜单
    public function getPositionPower(
        Request $request,
        System $system,
        SystemMenu $menuModel,
        SystemMenuDataPower $menu,
        Power $power
    ){
        $roles_id =  $request->get('roles_id');

        if (empty($roles_id)) return ReJson(message::$ERROR_CODE,message::$ERR_PARAM_EMPTY);

        //根据职位id查询对应菜单可见范围值
        $result = $power->getPersonList ($roles_id,$menu,$system);

        return ReJson(message::$SUCC_CODE,message::$SUCC_SELECT_DATA,$result);
    }

    //添加职位
    public function addAuthorityName(Request $request ,UserPosition $model)
    {
        try {
            $param = $request->post(['level_name']);

            if (empty($param)) Return ReJson(message::$ERROR_CODE,message::$ERR_PARAM_EMPTY);

            $result = $model->addLevel($param);

        }catch (ValidateException $e){

            return ReJson(message::$ERROR_CODE,$e->getMessage());
        }

        if ($result){
            $this->operateLog->addOperate($request->param ('user_login_id'),message::$ROLE_POWER,message::$SUCC_SYSTEM_ADD_JSQX);

            //添加成功查询一遍返回
            return ReJson(message::$SUCC_CODE,message::$SUCC_INSERT_DATA,$model->getLevelList());
        }

        return ReJson(message::$ERROR_CODE,message::$ERR_INSERT_DATA);

    }

    //修改职位昵称
    public function updateAuthorityName(Request $request,UserPosition $model)
    {
        try {
            $param = $request->post(['level_name','id']);

            Validate(userV::class)->scene('editName')->check($param);

            $result = $model->updateLevel($param);

        }catch (ValidateException $e){

            return ReJson(message::$ERROR_CODE,$e->getMessage());
        }

        if ($result){
            $this->operateLog->addOperate($request->param ('user_login_id'),message::$ROLE_POWER,message::$SUCC_SYSTEM_UPDATE_JSQX);

            return ReJson(message::$SUCC_CODE,message::$SUCC_UPDATE,$model->getLevelList());
        }

        return ReJson(message::$ERROR_CODE,message::$ERR_UPDATE);

    }

    //删除职位
    public function delAuthority(Request $request,SystemMenuDataPower $menu,User $user,UserPosition $position)
    {
        try {
            $id = $request->POST('id');

            if (empty($id)) return ReJson(message::$ERROR_CODE,message::$ERR_PARAM_EMPTY);

            //查询职位是否有生产权限数据
            $pdata = $menu->getPotionData($id);

            //查询职位是否有用户权限产生
            $udata = $user->getPotionData($id);

            //有生产数据否定删除
            if ($udata || !empty($pdata['menu_alias_id'])){
                return ReJson(message::$ERROR_CODE,message::$ERR_PRODUCE_DATA);
            }

            //删除操作
            $position->delLevel ($id);

            $this->operateLog->addOperate($request->param ('user_login_id'),message::$ROLE_POWER,message::$SUCC_SYSTEM_DEL_JSQX);

            return ReJson(message::$SUCC_CODE,message::$SUCC_DATELE_DATA);

        }catch (ValidateException $e){

            return ReJson(message::$ERROR_CODE,$e->getMessage());
        }

    }

    /**
     * 可见范围&功能权限
     */

    public function setAuthoritysafe(
        Request $request,
        SystemMenuDataPower $menu,
        System $systemSer,
        User $userModel
    ){
        /**
         * @param $utype //对应静态文件可见范围
         * @param $menu_id //菜单id
         * @param $roles_id  //职位id
         */

        $param = $request->post();
        Db::startTrans();
        try{
            Validate(Menu::class)->scene('addMenuDataPower')->check($param);

            //寻找菜单是否有父级关系

            $param['menu_alias_id'] = $systemSer->getMenuParentId($param['menu_alias_id']);

            //查询是否有该职位权限信息 true存在 修改 false 添加
            if ($menu->getPotionData($param['roles_id'])){

                $menu->editPositionData($param['roles_id'],$param);
            }else{

                $menu->addMenuPowerModel($param);
            }

            //编辑权限 退出用户登陆
            $idArr = $userModel->getPotionIdDataModel ($param['roles_id']);
            Db::table('login_token')->whereIn ('uid',$idArr)->delete ();
            Db::commit();
        }catch (ValidateException|\Exception $e){
            Db::rollback();
            return ReJson(message::$ERROR_CODE,$e->getMessage());
        }
        $this->operateLog->addOperate($request->param ('user_login_id'),message::$ROLE_POWER,message::$SUCC_SYSTEM_KJFW_JSQX);

        return ReJson(message::$SUCC_CODE,message::$SUCC_INSERT_DATA);
    }

/****************************************************************************用户管理*************************************************************/
    //查看用户列表
    public function getUserList(Request $request)
    {

        $page = $request->get ('page')?:1;
        $pageNum = $request->get ('pageNum')?:stateData::$_page;

        $where = [
            'type'=>stateData::$_company_type['user']
        ];

        $whereOr = [];

        if ($request->get ('level_id')){
            $where['level_id'] = $request->get ('level_id');
        }

        if ($request->get ('keys') && $request->get ('values')){
            $whereOr = [
                [$request->get ('keys'), 'like', '%'.$request->get ('values').'%'],
            ];
        }
//        Log::error ('角色'.$request->get ('level_id'));
        $pages['total'] = $this->user->getWhereUserCount ($where,$whereOr); //获取总条数

        $pages['pageNumber'] = $pageNum; //每页显示多少条

        return ReJson (message::$SUCC_CODE,message::$SUCC_SELECT_DATA,$this->user->getWhereUser($where,$whereOr,$page,$pageNum),$pages);

    }

    public function getUserPositionSelect(UserPosition $position)
    {
        return ReJson(message::$SUCC_CODE,message::$SUCC_SELECT_DATA,$position->getLevelList());
    }

    public function getUseruOrganizationSelect(UserOrganization $organization,System $system)
    {
        return ReJson(message::$SUCC_CODE,message::$SUCC_SELECT_DATA,$system->menuTreeList ($organization->getStructure()));
    }

    public function searchUser(Request $request)
    {
        $page = $request->get ('page')?:1;
        $pageNum = $request->get ('pageNum')?:stateData::$_page;

        $where = [
            'type'=>stateData::$_company_type['user']
        ];

        $whereOr = [];

        if ($request->get ('level_id')){
            $where['level_id'] = $request->get ('level_id');
        }

        if ($request->get ('keys') && $request->get ('values')){
            $whereOr = [
                [$request->get ('keys'), 'like', '%'.$request->get ('values').'%'],
            ];
        }
//        Log::error ('角色'.$request->get ('level_id'));
        $pages['total'] = $this->user->getWhereUserCount ($where,$whereOr); //获取总条数

        $pages['pageNumber'] = $pageNum; //每页显示多少条

        return ReJson (message::$SUCC_CODE,message::$SUCC_SELECT_DATA,$this->user->getWhereUser($where,$whereOr,$page,$pageNum),$pages);
    }


    //添加用户
    public function addUser(Request $request)
    {
        $param = $request->post();

        try {

            Validate(userV::class)->scene('adduser')->check($param);
            //查询数据库是否有该登陆账号 username
            if (!$this->user->checkUniqueName($param['username'])){
                return ReJson (message::$ERROR_CODE,message::$REG_USERNAME_REPEAT);
            }
            $result = $this->user->addBranchCompanyAccount($param,stateData::$_company_type['user']);

        }catch (ValidateException $e){
            return ReJson(message::$ERROR_CODE,$e->getMessage());
        }
        $this->operateLog->addOperate($request->param ('user_login_id'),message::$ROLE_POWER,message::$SUCC_SYSTEM_ADD_USER.$param['nickname']);

        if ($result){
            return ReJson(message::$SUCC_CODE,message::$SUCC_INSERT_DATA);
        }

        return ReJson(message::$ERROR_CODE,message::$ERR_INSERT_DATA);
    }

    //编辑用户
    public function editUser(Request $request,RedisService $redisService)
    {
        $param = $request->post();

        try {
            //查询数据库是否有该登陆账号 username
            if (!$this->user->checkUniqueName($param['username'],$param['id'])){
                return ReJson (message::$ERROR_CODE,message::$REG_USERNAME_REPEAT);
            }

//            Validate(userV::class)->scene('editUser')->check($param);
            //查询原有资料
            $userOldData = $this->user->getIdUserData ($param['id']);
            //是否修改了姓名|所属部门
            if ($userOldData['nickname'] != $param['nickname'] || $userOldData['department_id']['id'] != $param['department_id']){
                /**
                 * 更新统计部门缓存
                 */
                $redisService->updateStatisticsPerformanceUserInfo ($param);

            }
            $result = $this->user->editUserdata($param);

        }catch (ValidateException $e){
            return ReJson(message::$ERROR_CODE,$e->getMessage());
        }
        $this->operateLog->addOperate($request->param ('user_login_id'),message::$ROLE_POWER,message::$SUCC_SYSTEM_UPDATE_USER);
        if ($result){
            return ReJson(message::$SUCC_CODE,message::$SUCC_UPDATE);
        }


        return ReJson(message::$ERROR_CODE,message::$ERR_UPDATE);
    }

    //删除用户
    public function delUser(Request $request,System $systemService,CluePerson $cluePersonModel)
    {
        if (!$request->post('id')){
            return ReJson(message::$ERROR_CODE,message::$ERR_PARAM_EMPTY);
        }

        $id = $systemService->analysisId((string)$request->post('id'));

        /**
         * 判断是否有生产数据
         */
        //判断是否有线索库负责人信息
        if ($cluePersonModel->getFUidDataModel($id)){
            return ReJson (message::$ERROR_CODE,message::$ERR_CLUE_PERSON_NO_EMPTY_DEL);
        }

        //批量删除操作
        $this->user->delBranchAccount($id);

        //日志记录
        $this->operateLog->addOperate(
            $request->param ('user_login_id'),
            message::$Log_SYSTEM_SETTINGS,
            message::$SUCC_SYSTEM_DEL_USER.':'.$this->user->getIdNickName ($request->post('id'))
        );

        return ReJson(message::$SUCC_CODE,message::$SUCC_DATELE_DATA);

    }

    //重置密码
    public function rePassword(Request $request)
    {
        $id = $request->post('id');

        $reResult = $this->user->rePassword($id,stateData::$_password);

        $this->operateLog->addOperate($request->param ('user_login_id'),message::$ROLE_POWER,message::$SUCC_SYSTEM_RESETING_USER_PASSWORD);

        if ($reResult){
            return ReJson(message::$SUCC_CODE,message::$SUCC_REPASS);
        }
        return ReJson(message::$ERROR_CODE,message::$ERR_REPASS);
    }

    //启用||禁用
    public function EnableDisableUser(Request $request)
    {
        $param = $request->post();
        $uid = $request->param ('user_login_id');
        try {

            Validate(userV::class)->scene('dEUser')->check($param);

            //判断当前是开就赋值为关 关赋值为开
            if ($param['is_k'] == 1){ //关闭操作
                $opText = "关闭";
                $param['is_k_op_date'] = date('Y-m-d H:i:s');
            }else{ //开启操作
                $opText = "开启";
                $param['is_k_op_date'] = '';
            }
            //操作人
            $opName = $this->user->getIdNickName ($uid);
            //被操作人
            $uName = $this->user->getIdNickName ($param['id']);

            $result = $this->user->editUserdata($param);
            $upData = $this->user->getIdUserData($param['id']);

        }catch (ValidateException $e){
            return ReJson(message::$ERROR_CODE,$e->getMessage());
        }

        $this->operateLog->addOperate($uid,message::$ROLE_POWER,"用户：".$opName.$opText.' 账号:'.$uName);

        if ($result){
            return ReJson(message::$SUCC_CODE,message::$SUCC_UPDATE,$upData);
        }


        return ReJson(message::$ERROR_CODE,message::$ERR_UPDATE);
    }

    //是否设置为审批人
    public function systemFinanceUid(Request $request)
    {
        $param = $request->post();

        try {
//            Validate(userV::class)->scene('dEUser')->check($param);

            //判断当前是开就赋值为关 关赋值为开

            $result = $this->user->editUserdata($param);

            $upData = $this->user->getIdUserData($param['id']);

            $userName = $this->user->getIdNickName ($param['id']);

        }catch (ValidateException $e){

            return ReJson(message::$ERROR_CODE,$e->getMessage());
        }

        $this->operateLog->addOperate($request->param ('user_login_id'),message::$ROLE_POWER,"设置用户：".$userName.' 为审批人');
        if ($result){
            return ReJson(message::$SUCC_CODE,message::$SUCC_UPDATE,$upData);
        }


        return ReJson(message::$ERROR_CODE,message::$ERR_UPDATE);
    }

    //是否设置为特价证书审批人
    public function systemSpecialOffer(Request $request)
    {
        $param = $request->post();
        try {
            //判断当前是开就赋值为关 关赋值为开
            $result = $this->user->editUserdata($param);

            $upData = $this->user->getIdUserData($param['id']);

            $userName = $this->user->getIdNickName ($param['id']);

        }catch (ValidateException $e){
            return ReJson(message::$ERROR_CODE,$e->getMessage());
        }

        $this->operateLog->addOperate($request->param ('user_login_id'),message::$ROLE_POWER,"设置用户：".$userName." 为特价证书审批人");
        if ($result){
            return ReJson(message::$SUCC_CODE,message::$SUCC_UPDATE,$upData);
        }

        return ReJson(message::$ERROR_CODE,message::$ERR_UPDATE);
    }



    //设置用户签名
    public function setUserSignature(Request $request,User $user,SystemOperateLog $systemOperateLog)
    {
        $id = $request->param('user_login_id');

        $param = $request->post ();
        unset($param['user_login_id']);

        if (empty($id)) return ReJson (message::$ERROR_CODE,message::$ERR_PARAM_EMPTY);

        $user->setSignTextModel($id,$param);
        //添加系统日志
        $systemOperateLog->addOperate($id, message::$Log_SYSTEM_SETTINGS, "设置用户签名");

        return ReJson (message::$SUCC_CODE,message::$SUCC_UPDATE);
    }

    public static function getDepartmentAllUser($department_id)
    {
        $model = new UserOrganization();
        $department_ids = $model->getDataRangeDepartmentList([],$department_id);
        $department_ids[] = (int)$department_id;
        sort($department_ids);
        return $department_ids;

    }
}